//
//  SISSFindNewHouseViewController.m
//  SISSAPP
//
//  Created by 袁应荣 on 2017/12/14.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSFindNewHouseViewController.h"
#import "SISSSearchViewController.h"
#import "SISSComboBoxViewNewHouse.h"
#import "SISSFindNewHouseCell.h"
#import "SISSHousingProjectViewController.h"
#import "SISSJsonRequestNetworkingManager+Resources.h"

@interface SISSFindNewHouseViewController ()<UITableViewDelegate,UITableViewDataSource,SISSComboBoxViewNewHouseDelegate,UISearchBarDelegate>

/// 房源数组
@property (strong, nonatomic) NSMutableArray<SISSNewHouseBuildingModel *> *newHouseBuildingArr;

/// searchBar
@property (weak, nonatomic) UISearchBar *searchBar;
/// tableView
@property (weak, nonatomic) SISSBaseTableView *tableView;
/// 筛选视图
@property (weak, nonatomic) SISSComboBoxViewNewHouse *filterView;

// hintLabel
@property (weak, nonatomic) UILabel *hintLabel;

/// 排序规则
@property (copy, nonatomic) NSString *order;
/// 住宅类型
@property (copy, nonatomic) NSString *htype;
/// 县区
@property (copy, nonatomic) NSString *town;
/// 价格
@property (copy, nonatomic) NSString *price;
/// 建筑形式
@property (copy, nonatomic) NSString *btype;
/// 面积
@property (copy, nonatomic) NSString *bsqaur;
/// 地铁
@property (copy, nonatomic) NSString *subway;
/// 销售状态
@property (copy, nonatomic) NSString *sellKind;
/// pageNo
@property (assign, nonatomic) NSInteger pageNo;

@end

@implementation SISSFindNewHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.pageNo = 1;
    [self requestFilterSearchNewHouseBuildingData];
    
    WeakSelf
    [kSISSRefresh prepareHeaderRefresh:self.tableView loadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeUpDown;
        [weakSelf upDownLoadData];
    }];
    
    
    [kSISSRefresh prepareFooterRefresh:self.tableView reloadDataBlock:^{
        kSISSRefresh.refreshType = SISSRefressTypeReloadMore;
        [weakSelf reloadMoreData];
    }];
    
    self.tableView.mj_footer.hidden = YES;
}


- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.filterView.comBoBoxView dismissPopView];
}

#pragma mark - 代理
#pragma mark -- SISSComboBoxViewDelegate 筛选
- (void)comboBoxViewDidSelectDisplayTypeNormalWithRootItemTitle:(NSString *)rootItemTitle selectedPath:(nonnull MMSelectedPath *)selectedPath title:(nonnull NSString *)title {
    NSString *firstPath = selectedPath.firstPath == 0 ? @"" : [NSString stringWithFormat:@"%02zd",selectedPath.firstPath];
    if ([rootItemTitle isEqualToString:@"区域"]) {
        self.town = firstPath;
    } else if ([rootItemTitle isEqualToString:@"价格"]) {
        if (selectedPath.firstPath == 0) {
            self.price = @"";
        } else if (selectedPath.firstPath == 1) {
            self.price = @"0~7000";
        } else if (selectedPath.firstPath == 9) {
            self.price = @"40000~max";
        } else {
            self.price = [title stringByReplacingOccurrencesOfString:@"-" withString:@"~"];
        }
        
    } else if ([rootItemTitle isEqualToString:@"面积"]) {
        if (selectedPath.firstPath == 0) {
            self.bsqaur = @"";
        } else if (selectedPath.firstPath == 1) {
            self.bsqaur = @"0~60";
        } else if (selectedPath.firstPath == 6) {
            self.bsqaur = @"180~max";
        } else {
            self.bsqaur = [title stringByReplacingOccurrencesOfString:@"-" withString:@"~"];
        }
    } else if ([rootItemTitle isEqualToString:@"建筑形式"]) {
        self.btype = firstPath;
    }
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;
    self.pageNo = 1;
    [self requestFilterSearchNewHouseBuildingData];
    
}

- (void)comboBoxViewDidSelectDisplayTypeCustomMoreWithTitle:(NSString *)title selectedPath:(nonnull MMSelectedPath *)selectedPath subtitle:(nonnull NSString *)subtitle {
    NSString *secondPath = selectedPath.secondPath == 0 ? @"" : [NSString stringWithFormat:@"%02zd",selectedPath.secondPath];
    if ([title isEqualToString:@"住宅类型"]) {
        self.htype = secondPath;
    } else if ([title isEqualToString:@"地铁"]) {
        self.subway = secondPath;
    } else if ([title isEqualToString:@"销售状态"]) {
        if (selectedPath.secondPath == 0) {
            self.sellKind = @"";
        } else if (selectedPath.secondPath == 1) { // 在售
            self.sellKind = @"1";
        } else if (selectedPath.secondPath == 2) { // 认筹
            self.sellKind = @"0";
        }
    }
}


- (void)comboBoxViewDisplayTypeFiltersConfirmClickAction {
    
    self.pageNo = 1;
    [self requestFilterSearchNewHouseBuildingData];
    kSISSRefresh.refreshType = SISSRefressTypeUpDown;

}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
    self.searchBar.showsCancelButton = YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    self.keyWords = searchBar.text;
    self.pageNo = 1;
    [self requestFilterSearchNewHouseBuildingData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    self.searchBar.showsCancelButton = NO;
    [self.searchBar resignFirstResponder];
}

#pragma mark -- UITableViewDelegate & UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    [tableView tableViewDisplayWithMessage:@"没有找到相关房源！" ifNecessaryForRowCount:self.newHouseBuildingArr.count];
    if (self.newHouseBuildingArr.count != 0) {
        return self.newHouseBuildingArr.count;
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SISSFindNewHouseCell *cell = [tableView dequeueReusableCellWithIdentifier:findNewHouseCellReuseID forIndexPath:indexPath];
    cell.houseBuildingModel = self.newHouseBuildingArr[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES]; // 去除tableView的选中状态
    SISSHousingProjectViewController *vc = [[SISSHousingProjectViewController alloc] init];

    SISSNewHouseBuildingModel *houseBuilingModel = self.newHouseBuildingArr[indexPath.row];
    vc.builingName = houseBuilingModel.pname;
//    if (houseModel.read != 1) {
//
//        [kNetworkManager setHouseResourceReadWithHouseId:houseModel.ID success:^(id responseObject) {
//
//            if ([responseObject[@"code"] integerValue] == 200) {
//                NSLog(@"插入成功！");
//            }
//
//        } failed:^(NSError *error) {
//
//            NSLog(@"%@",error);
//        }];
//    }
//    self.newHouseBuildingArr[indexPath.row].read = 1;
//    [self.tableView reloadData];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark - 点击排序按钮
- (void)sortedButtonDidClick:(UIButton *)button {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    alertController.view.tintColor = [UIColor blackColor];
    [alertController addTapDisMissAction];
    
    NSArray *sortArr = @[@"默认排序", @"价格从低到高", @"价格从高到低", @"可售套数从低到高", @"可售套数从高到低", @"关注度从低到高", @"关注度从高到低"];
    
    for (NSInteger i = 0; i < sortArr.count; i++) {
        UIAlertAction *action = [UIAlertAction actionWithTitle:sortArr[i] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            self.order = i == 0 ? @"" : [NSString stringWithFormat:@"%02zd",i];;
            kSISSRefresh.refreshType = SISSRefressTypeUpDown;
            self.pageNo = 1;
            [self requestFilterSearchNewHouseBuildingData];
        }];
        
        [alertController addAction:action];
    }
    
    [self presentViewController:alertController animated:YES completion:nil];
}

#pragma mark - 上下拉刷新加载方法
- (void)upDownLoadData {
    
    self.pageNo = 1;
    
    [self requestFilterSearchNewHouseBuildingData];
    
}

- (void)reloadMoreData {
    
    self.pageNo += 1;
    
    [self requestFilterSearchNewHouseBuildingData];
}



#pragma mark - 2.4.1 筛选房源、找房源的请求
- (void)requestFilterSearchNewHouseBuildingData {
    
    // 非空处理
    NSString *keyWords = self.keyWords ? self.keyWords : @"";
    NSString *bsqaur = self.bsqaur ? self.bsqaur : @"";
    NSString *btype = self.btype ? self.btype : @"";
    NSString *htype = self.htype ? self.htype : @"";
    NSString *order = self.order ? self.order : @"";
    NSString *price = self.price ? self.price : @"";
    NSString *sellKind = self.sellKind ? self.sellKind : @"";
    NSString *subway = self.subway ? self.subway : @"";
    NSString *town = self.town ? self.town : @"";
    NSDictionary *parameters = @{
                                 @"bsqar": bsqaur,
                                 @"btype": btype,
                                 @"htype": htype,
                                 @"keyWords": keyWords,
                                 @"order": order,
                                 @"pageNo": @(self.pageNo),
                                 @"pageSize": @"20",
                                 @"price": price,
                                 @"sellKind": sellKind,
                                 @"subway": subway,
                                 @"town": town
                                 };
    //加载搜索跳转找新房的数据
    WeakSelf
    [kJsonRequestNetworkingManager requestFilterNewHouseResourceWithParameters:parameters success:^(SISSNewHouseListModel *newHouseListModel) {
        
        if (weakSelf.newHouseBuildingArr.count != 0 && kSISSRefresh.refreshType == SISSRefressTypeUpDown) {
            
            [weakSelf.newHouseBuildingArr removeAllObjects];
        }
        
        for (int i = 0; i < newHouseListModel.buildList.count; i++) {
            
            [weakSelf.newHouseBuildingArr addObject:newHouseListModel.buildList[i]];
        }

        [[NSOperationQueue mainQueue] addOperationWithBlock:^{

            [weakSelf.tableView reloadData];
            weakSelf.tableView.mj_footer.hidden = [newHouseListModel.pnameCount integerValue] == 0;
            [weakSelf.tableView.mj_header endRefreshing];
            [weakSelf.tableView.mj_footer endRefreshing];
            if (weakSelf.newHouseBuildingArr.count >= [newHouseListModel.pnameCount integerValue]) {
//                weakSelf.tableView.mj_footer.hidden = YES;
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            }
        }];


    } failed:^(NSError *error) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        NSLog(@"%@",error);
    }];
    
}



#pragma mark - 设置UI
- (void)setupSubviews {
    [super setupSubviews];
    
    UISearchBar *searchBar = [[UISearchBar alloc] init];
    searchBar.placeholder = @"楼盘名/开发商/品牌";
    searchBar.delegate = self;
//    searchBar.backgroundColor = [UIColor groupTableViewBackgroundColor];
    UITextField *searchField=[searchBar valueForKey:@"searchField"];
    searchField.backgroundColor = [UIColor groupTableViewBackgroundColor]; // 以此来设置搜索框中的颜色
    searchBar.backgroundImage = [UIImage new];
    searchBar.barTintColor = MAIN_TEXT_COLOR;
    searchBar.tintColor = SECONDARY_TEXT_COLOR;
    [self.view addSubview:searchBar];
    self.searchBar = searchBar;
    
    [self.searchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.left.right.equalTo(self.view);
    }];
    
    // 添加筛选视图
    SISSComboBoxViewNewHouse *filterView = [[SISSComboBoxViewNewHouse alloc] initWithFrame:CGRectMake(0, NAVIGATION_HEIGHT + 55, SCREEN_WIDTH, 44)];
    filterView.delegate = self;
    
    [self.view addSubview:filterView];
    self.filterView = filterView;
    
    SISSBaseTableView *tableView = [[SISSBaseTableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    
    tableView.dataSource = self;
    tableView.delegate = self;
    // 自动行高
    tableView.estimatedRowHeight = 80;
    tableView.rowHeight = UITableViewAutomaticDimension;
    if (@available(iOS 11.0, *)) {
        tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentAutomatic;
    }
    [tableView registerClass:[SISSFindNewHouseCell class] forCellReuseIdentifier:findNewHouseCellReuseID];
    
    [self.view addSubview:tableView];
    self.tableView = tableView;
    
    // 排序按钮
    UIButton *sortButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [sortButton setTitle:@"排序" forState:UIControlStateNormal];
    sortButton.layer.cornerRadius = 12;
    sortButton.layer.masksToBounds = YES;
    [sortButton setBackgroundImage:[ImageWithColor imageWithColor:[UIColor darkGrayColor]]  forState:UIControlStateNormal];
    sortButton.titleLabel.font = [UIFont systemFontOfSize:15];
    sortButton.alpha = 0.8;
    [sortButton addTarget:self action:@selector(sortedButtonDidClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sortButton];
    
    // 自动布局
    CGSize sortBtnSize = CGSizeMake(66, 30);
    CGFloat margin = 10;
    CGFloat bottomViewHeight = 0;
    WeakSelf
    [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.filterView.mas_bottom);
        make.left.right.equalTo(weakSelf.view);
        make.bottom.mas_equalTo(-bottomViewHeight);
    }];
    
    [sortButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(weakSelf.view).offset(-4 * margin);
        make.bottom.equalTo(weakSelf.view).offset(-8 * margin);
        make.size.mas_equalTo(sortBtnSize);
    }];
    
}

#pragma mark - Getter & Setter

- (NSMutableArray<SISSNewHouseBuildingModel *> *)newHouseBuildingArr {
    if (!_newHouseBuildingArr) {
        _newHouseBuildingArr = [NSMutableArray array];
    }
    return _newHouseBuildingArr;
}


@end
